<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 17/8/5
 * Time: 下午4:37
 */
namespace app\api\controller\v1;

use app\common\lib\exception\ApiException;
use think\Controller;
use app\common\lib\aes\Aes;
use app\api\model\User;

/**
 * 客户端auth登录权限基础类库
 * 1、每个接口(需要登录）都需要去集
 * 2、判定 access_user_token 是否合法
 * 3、用户信息 - 》 user
 * Class AuthBase
 * @package app\api\controller
 */
class AuthBase extends Common {

    /**
     * 登录用户的基本信息
     * @var array
     */
    public $user = [];

    /**
     * 初始化
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function _initialize() {
        parent::_initialize();
        if(empty($this->isLogin())) {
            //return show(config('code.error'),'请重新登录！',[],'10003');
            throw new ApiException('请重新登录！',403,10003);
        }
    }

    /**
     * 判定是否登录
     * @author 王柯 <wangke.email@foxmail.com>
     * @return bool
     */
    public function isLogin() {
        //jXorqluebyWxdFu3RN9WurudJccGeTBLcNkTueitrjaYpzKSSpKjoG0Vhoy+90VD
        //user1登录测试token Zc9t+7lNWXY+6+2uSUoZ4jZzTlAf5sNGaq9Z/W608py/UJK/zUHutycdSKacqsH7
        //user1 read 测试token Zc9t+7lNWXY+6+2uSUoZ4jZzTlAf5sNGaq9Z/W608pz1V5RIR54J6PLN8RuBjwj9
        //user1 get_user_info 测试token Zc9t+7lNWXY+6+2uSUoZ4jZzTlAf5sNGaq9Z/W608pz1V5RIR54J6PLN8RuBjwj9
        if(empty($this->headers['access-user-token'])) {
            return false;
        }
        //halt($this->headers);
        $obj = new Aes();
        $accessUserToken = $obj->decrypt($this->headers['access-user-token']);
        if(empty($accessUserToken)) {
            return false;
        }
        //halt($obj->decrypt('Zc9t+7lNWXY+6+2uSUoZ4jZzTlAf5sNGaq9Z/W608py/UJK/zUHutycdSKacqsH7'));
        if(!preg_match('/||/', $accessUserToken)) {
            return false;
        }
        //halt($accessUserToken);
        list($token,$id) = explode("||", $accessUserToken);
        //list($token) = explode("||", $accessUserToken);
       // halt($token);
        $user = User::get(['token' => $token]);
        //halt($user->stop_status);
        if(!$user || $user->stop_status == '已停用') {
            return false;
        }

        // 判定时间是否过期
        if(time() > $user->time_out) {
            return false;
        }

        $this->user = $user;
        return true;
    }
}